import { CozeAPI, ChatEventType, ChatStatus, COZE_CN_BASE_URL, RoleType } from '@coze/api';
import dotenv from 'dotenv';
import path from 'path';
import { fileURLToPath } from 'url';

// 获取当前文件的目录
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

// 加载环境变量
dotenv.config({ path: path.join(__dirname, '..', '.env') });

const token = process.env.COZE_API_TOKEN;
const botId = process.env.COZE_BOT_ID;

if (!token || !botId) {
  console.error('错误: 请确保 .env 文件中设置了 COZE_API_TOKEN 和 COZE_BOT_ID');
  process.exit(1);
}

// 创建 Coze API 客户端
const client = new CozeAPI({
  token,
  baseURL: COZE_CN_BASE_URL,
});

// 测试流式对话
const testStreamChat = async (message = '你好，请介绍一下自己') => {
  try {
    console.log('=== 测试 Coze API 流式对话 ===');
    console.log(`使用 Bot ID: ${botId}`);
    console.log(`发送消息: "${message}"`);
    
    console.log('\n开始接收流式响应...');
    const stream = await client.chat.stream({
      bot_id: botId,
      additional_messages: [
        {
          role: RoleType.User,
          content: message,
          content_type: 'text',
        },
      ],
    });

    let fullResponse = '';
    
    for await (const part of stream) {
      if (part.event === ChatEventType.CONVERSATION_MESSAGE_DELTA) {
        process.stdout.write(part.data.content); // 实时输出
        fullResponse += part.data.content;
      }
    }
    
    console.log('\n\n=== 完整回复 ===');
    console.log(fullResponse);
    console.log('\n=== 测试完成 ===');
    
  } catch (error) {
    console.error('\n错误:', error.message);
    if (error.response) {
      console.error('错误响应:', {
        status: error.response.status,
        data: error.response.data
      });
    }
  }
};

// 测试非流式对话（使用 createAndPoll 方法）
const testNonStreamChat = async (message = '你好，请介绍一下自己') => {
  try {
    console.log('=== 测试 Coze API 非流式对话 ===');
    console.log(`使用 Bot ID: ${botId}`);
    console.log(`发送消息: "${message}"`);
    
    console.log('\n发送请求并等待完成...');
    const response = await client.chat.createAndPoll({
      bot_id: botId,
      additional_messages: [
        {
          role: RoleType.User,
          content: message,
          content_type: 'text',
        },
      ],
    });

    if (response.chat.status === ChatStatus.COMPLETED) {
      console.log('\n=== 对话完成 ===');
      console.log('Token 使用情况:', response.chat.usage);
      
      console.log('\n所有消息:');
      for (const item of response.messages) {
        console.log(`\n[${item.role}]:[${item.type}]:`);
        if (item.content && item.content.length > 100) {
          console.log(`${item.content.substring(0, 100)}...`);
        } else {
          console.log(item.content);
        }
      }
      
      // 找到AI的回复消息
      const aiMessages = response.messages.filter(
        msg => msg.role === 'assistant' && msg.type === 'answer'
      );
      
      if (aiMessages.length) {
        console.log('\n=== AI 回复 ===');
        console.log(aiMessages[0].content);
      } else {
        console.log('\n没有找到 AI 回复');
      }
    } else {
      console.log(`\n对话未完成，状态: ${response.chat.status}`);
    }
    
    console.log('\n=== 测试完成 ===');
    
  } catch (error) {
    console.error('\n错误:', error.message);
    if (error.response) {
      console.error('错误响应:', {
        status: error.response.status,
        data: error.response.data
      });
    }
  }
};

// 执行测试
const userMessage = process.argv[2] || '你好，请介绍一下自己';
const testMode = process.argv[3] || 'both';

if (testMode === 'stream' || testMode === 'both') {
  testStreamChat(userMessage).then(() => {
    if (testMode === 'both') {
      console.log('\n\n');
      testNonStreamChat(userMessage);
    }
  });
} else if (testMode === 'non-stream') {
  testNonStreamChat(userMessage);
}